/*
 * @Author: xia.duanjian
 * @Date: 2022-09-18 10:43:48
 * @LastEditors: xia.duanjian
 * @LastEditTime: 2022-09-18 10:47:57
 * @Description: sessionStorage与localStorage本地存储
 */

export default {
  setLocal (key, value) {
    if (value === undefined) {
      return this.clearLocal(key)
    }
    window.localStorage.setItem(key, JSON.stringify(value))
  },
  getLocal (key) {
    const obj = window.localStorage.getItem(key)
    if (obj && obj !== 'undefined' && obj !== 'null') {
      return JSON.parse(obj)
    }
  },
  clearOneLocal (key) {
    window.localStorage.removeItem(key)
  },
  clearAllLocal () {
    window.localStorage.clear()
  },
  setSession (key, value) { // 正常设置，会覆盖原值
    if (value === undefined) {
      return this.clearOneSession(key)
    }
    window.sessionStorage.setItem(key, JSON.stringify(value))
  },
  appendSession (key, value) { // 追加赋值，不会覆盖原值
    if (window.sessionStorage.getItem(key)) {
      const oldValue = JSON.parse(window.sessionStorage.getItem(key))
      const newValue = Object.assign(oldValue, value)
      window.sessionStorage.setItem(key, JSON.stringify(newValue))
    } else {
      window.sessionStorage.setItem(key, JSON.stringify(value))
    }
  },
  getSession (key) { // 需要判断取值格式，如果是string或者undefined，不能JSON.PARSE()
    const obj = window.sessionStorage.getItem(key)
    if (obj && obj !== 'undefined' && obj !== 'null') {
      return JSON.parse(obj)
    }
    return ''
  },
  clearOneSession (key) {
    window.sessionStorage.removeItem(key)
  },
  clearAllSession () {
    window.sessionStorage.clear()
  }
}
